import React, { useEffect, useState, } from "react"
import styles from './msgboard.less';
import { Pagination, Form, Input, Button, Modal, message } from 'antd';
import { AliwangwangOutlined } from '@ant-design/icons';
import { IMsgboard } from '@/utils/msgabroad'
import { useSelector, useDispatch, IRouteComponentProps } from 'umi';
import Read from '@/components/Read';
import { IPages } from "@/utils/about";
import { addmsg, getMessage } from "@/services";
var moment = require('moment');
const { TextArea } = Input;
const Msgboard: React.FC<IRouteComponentProps> = ({ location }) => {
    const result = useSelector((state: { msgboard: any; }) => state.msgboard)
    const dispatch = useDispatch();
    //评论列表分页
    let [list, setlist] = useState<IMsgboard[]>([]);
    let [contentLen, setcontentLen] = useState(0);
    let params: IPages = { page: 1, pageSize: 6 };
    let [pages, getPages] = useState(1);
    //获取评论数据
    useEffect(() => {
        // dispatch({
        //     type: "msgboard/getMessage",
        // });
        if (pages) {
            params = { ...params, page: pages, pageSize: 6 }
        } else {
            params = { ...params, page: pages, pageSize: 6 }
        }
        getMessage(params).then(ok => {
            ok.data[0].forEach((item: any) => {
                item.isFlag = false;
                item.children.forEach((item1: any) => {
                    item1.isFlag = false
                })
            })
            setlist(ok.data[0]);
            setcontentLen(ok.data[1])
        })
    }, [pages]);
    const [isFlag, setIsFlag] = useState(false)
    //修改flag
    const setflag = (id: string) => {
        if (localStorage.getItem('user')) {
            list.forEach(item => {
                if (item.id == id) {
                    item.isFlag = !item.isFlag;
                }
                if (item.children) {
                    item.children.forEach(item1 => {
                        if (item1.id == id) {
                            item1.isFlag = !item1.isFlag;
                        }
                    })
                }
            })
        } else {
            showModal()
        }
    };
    //评论点击全局提示
    const success = () => {
        message.success('评论成功,已提交审核');
    };
    //随机背景色
    function randomColor() {
        var arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']; // 下标 [0-15]
        var str = '#';
        //生成0-15随机下标
        for (var i = 1; i <= 6; i++) {
            var index = Math.floor(Math.random() * 16);
            str += arr[index];
        };
        return str;
    };
    //时间差
    function dateFormat(date: any) {
        let m2 = moment();  //当下时间
        // let m2=moment('2019-12-18 10:10:00');
        let m1 = moment(date);
        let du = moment.duration(m2 - m1, 'ms');   //做差
        let months = du.get("months")
        let days = du.get('days');
        let hours = du.get('hours');
        let mins = du.get('minutes');
        //  输出结果为   01天08时09分40秒
        if (months > 0) {
            return (months + 1) + "个月之前"
        } else if (days > 0) {
            return days + "天之前"
        } else if (hours > 0) {
            return hours + '小时之前'
        } else {
            return mins + '分钟之前'
        }
    };
    //输入框聚焦判断有没有用户名
    const bounced = () => {
        if (!localStorage.getItem('user')) {
            showModal()
        }
    };
    //弹框
    const [isModalVisible, setIsModalVisible] = useState(false);
    const showModal = () => {
        setIsModalVisible(true);
    };
    const handleOk = () => {
        setIsModalVisible(false);
    };
    const handleCancel = () => {
        setIsModalVisible(false);
    };
    //本地存储账户
    const finishuser = (values: any) => {
        localStorage.setItem('user', JSON.stringify(values));
        handleCancel()
    };
    //发布按钮
    const onFinish = (values: any) => {
        if (localStorage.getItem('user')) {
            let data = JSON.parse(localStorage.getItem('user') as any);
            let params = {
                name: data.name,
                email: data.email,
                content: values.content,
                url: location.pathname,
                hostId: "8d8b6492-32e5-44e5-b38b-9a479d1a94bd"
            };
            addmsg(params).then(ok => {
                success()
            })
        } else {
            showModal()
        }
    };
    let [content, setcontent] = useState('')
    return (
        <div className={styles.box}>
            <div className={styles.title}>
                <p>留言板</p>
                <p>[ 请勿灌水 ]</p>
            </div>
            <div className={styles.msgboard}>
                <div className={styles.h1}>评论</div>
                <div className={styles.publish}>
                    <Form className={styles.form} onFinish={onFinish}>
                        <Form.Item className={styles.pub}
                            name="content"
                            rules={[{ required: true, message: 'Please input your content!' }]}
                        >
                            <TextArea rows={4} placeholder='请输入内容(支持MarkDown)' value={content} onChange={(e) => { setcontent(e.target.value) }} onClick={() => {
                                bounced()
                            }} className={styles.text} />
                        </Form.Item>
                        <Form.Item className={styles.fItem}>
                            <span>表情</span>
                            <>
                                {
                                    content.length > 0 ? <Button type="primary" danger htmlType="submit">发布</Button>
                                        : <Button type="primary" disabled>发布</Button>
                                }
                                <Modal title="请设置你的信息" footer={null} visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>
                                    <Form onFinish={finishuser}>
                                        <Form.Item
                                            label="名称"
                                            name="name"
                                            rules={[{ required: true, message: '请输入账户!' }]}
                                        >
                                            <Input />
                                        </Form.Item>
                                        <Form.Item
                                            label="邮箱"
                                            name="email"
                                            rules={[
                                                { required: true, message: '请输入合法邮箱地址!' },
                                                {
                                                    pattern: /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/,
                                                    message: "格式不正确！"
                                                }
                                            ]}
                                        >
                                            <Input />
                                        </Form.Item>
                                        <p style={{ display: "flex", justifyContent: 'flex-end' }}>
                                            <Button htmlType="submit" type='primary'>保存</Button>
                                            <Button onClick={handleCancel}>取消</Button>
                                        </p>
                                    </Form>
                                </Modal>
                            </>
                        </Form.Item>
                    </Form>
                </div>
                <div className={styles.msg}>
                    {
                        list && list.map((item: IMsgboard, index: number) => {
                            return <div key={index} className={styles.item}>
                                <p>
                                    <span style={{ background: randomColor() }}>{item.name.charAt(0).toUpperCase()}</span>
                                    <span>{item.name}</span>
                                </p>
                                <p dangerouslySetInnerHTML={{
                                    __html: item.content
                                }}></p>
                                <p><span>{item.userAgent}</span><span>{dateFormat(item.createAt)}</span><span ><AliwangwangOutlined /><span onClick={() => {
                                    setIsFlag(isFlag ? false : true)
                                    setflag(item.id);
                                }}>回复</span></span></p>
                                {
                                    item.isFlag ? <Form className={styles.form}>
                                        <Form.Item className={styles.cont}
                                            name=""
                                            rules={[{ required: true, message: 'Please input your content!' }]}
                                        >
                                            <TextArea rows={4} placeholder={`回复 ${item.name} :`} className={styles.text} />
                                        </Form.Item>
                                        <p>
                                            <Button onClick={() => {
                                                setIsFlag(isFlag ? false : true)
                                                setflag(item.id);
                                            }}>收起</Button>
                                            <Button type="primary" htmlType="submit" onClick={() => {
                                                setIsFlag(isFlag ? false : true)
                                                setflag(item.id);
                                                success()
                                            }}>发布</Button>
                                        </p>
                                    </Form> : ''
                                }
                                {
                                    item.children.map((item1, index1) => {
                                        return <div key={index1} className={styles.children}>
                                            <p>
                                                <span style={{ background: randomColor() }}>{item1.name.charAt(0).toUpperCase()}</span>
                                                <span>{item1.name}</span>
                                                <span >回复</span>
                                                <span>{item.name}</span>
                                            </p>
                                            <p dangerouslySetInnerHTML={{
                                                __html: item1.content
                                            }}></p>
                                            <p><span>{item1.userAgent}</span><span>{dateFormat(item1.createAt)}</span><span><AliwangwangOutlined /><span onClick={() => {
                                                setIsFlag(isFlag ? false : true)
                                                setflag(item1.id);
                                            }}>回复</span></span></p>
                                            {
                                                item1.isFlag ? <Form className={styles.form}>
                                                    <Form.Item className={styles.cont}
                                                        name=""
                                                        rules={[{ required: true, message: 'Please input your content!' }]}
                                                    >
                                                        <TextArea rows={4} placeholder={`回复 ${item1.name} :`} className={styles.text} />
                                                    </Form.Item>
                                                    <p>
                                                        <Button onClick={() => {
                                                            setIsFlag(isFlag ? false : true)
                                                            setflag(item1.id);
                                                        }}>收起</Button>
                                                        <Button type="primary" htmlType="submit" onClick={() => {
                                                            setIsFlag(isFlag ? false : true)
                                                            setflag(item.id);
                                                            success()
                                                        }}>发布</Button>
                                                    </p>
                                                </Form> : ''
                                            }
                                        </div>
                                    })
                                }
                            </div>
                        })
                    }
                </div>
                {/* 分页 */}
                <div className={styles.page}>
                    <Pagination
                        defaultCurrent={1}
                        total={contentLen}
                        defaultPageSize={6}
                        onChange={(e) => { getPages(e) }}
                    />
                </div>
            </div>
            <div className={styles.bottom}>
                <p>推荐阅读</p>
                <Read />
            </div>
        </div>
    );
}
export default Msgboard